package filter;

import com.alibaba.fastjson.JSON;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     //  所以的请求都先到达这里，经过检查后，决定是否发给后面对应Servlet
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String[] urls={"/api/books","/api/activeUser","/api/hotBooks","/api/notice","/api/login","/api/register"};//
        String path=request.getRequestURL().toString();
        System.out.println(path);
        boolean fangxing=false;
        for (String url:urls){
            if(path.indexOf(url)>0) {
                fangxing = true;
                break;

            }
        }
        if (fangxing==false) {


        HttpSession session =request.getSession();//这行代码会自动根据请求消息中头部set.cookie键带的值来获取对应session
        //怎么分析这个session对象是本次新创建的，还是上一次创建的;登录时创建的session添加一个属性user到里面，
        Object user=session.getAttribute("user");
        Response build=null;
        if(user==null) {//该浏览器还没有登录
            build = Response.build(ResponseCode.NOT_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSON(build).toString());
           }
        }else{//已经登录，放行，该请求继续访问后面的servlet
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
